from hurryoff.core.router import PathPart
import datetime, time, simplejson

class JSONDateTimeEncoder(simplejson.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (datetime.date, datetime.datetime, datetime.time)):
            return obj.strftime('%H:%M')
        if isinstance(obj, PathPart):
            return obj.__dict__
        else:
            return simplejson.JSONEncoder.default(self, obj)

def parseTime(source):
    if source != '':
        timeInfo = time.strptime(source, "%H.%M")
        return datetime.time(timeInfo.tm_hour, timeInfo.tm_min)
    return None

def getTimeDeltaInSeconds(time1, time2):
    seconds2 = datetime.timedelta(days=0 if time2 > time1 else 1, hours=time2.hour, minutes=time2.minute).total_seconds()
    seconds1 = datetime.timedelta(days=0, hours=time1.hour, minutes=time1.minute).total_seconds()
    return seconds2 - seconds1

def convertSecondsToHoursMinutes(seconds):
    hours = int(seconds / (60*60))
    minutes = seconds / 60 - 60*hours
    return hours, minutes

def getTimeDelta(time1, time2):
    return convertSecondsToHoursMinutes(getTimeDeltaInSeconds(time1, time2))

def jsonDumpObject(object):
    return simplejson.dumps(object, cls=JSONDateTimeEncoder)
